<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>多线程 | 浪飞IT小栈</title>
    <meta name="generator" content="VuePress 1.9.9">
    <link rel="icon" href="/img/favicon.ico">
    <meta name="description" content="前后端技术分享">
    <meta name="keywords" content="前端博客,后端博客,人工智能,个人技术博客,前端,前端开发,前端框架,web前端,前端面试题,技术文档,学习,面试,JavaScript,js,ES6,TypeScript,vue,python,css3,html5,Node,git,github,markdown,java,Spring,Springboot,Redis,mysql">
    <meta name="baidu-site-verification" content="7F55weZDDc">
    <meta name="theme-color" content="#11a8cd">
    
    <link rel="preload" href="/assets/css/0.styles.ada71c49.css" as="style"><link rel="preload" href="/assets/js/app.a2a00aa5.js" as="script"><link rel="preload" href="/assets/js/2.256f807a.js" as="script"><link rel="preload" href="/assets/js/26.abc5dea3.js" as="script"><link rel="prefetch" href="/assets/js/10.ab144fe3.js"><link rel="prefetch" href="/assets/js/11.062e0879.js"><link rel="prefetch" href="/assets/js/12.f9c60882.js"><link rel="prefetch" href="/assets/js/13.0a6ebfcf.js"><link rel="prefetch" href="/assets/js/14.03fc6f12.js"><link rel="prefetch" href="/assets/js/15.19dbf9fd.js"><link rel="prefetch" href="/assets/js/16.6e68160b.js"><link rel="prefetch" href="/assets/js/17.1d678834.js"><link rel="prefetch" href="/assets/js/18.4536fd5c.js"><link rel="prefetch" href="/assets/js/19.9c1b65df.js"><link rel="prefetch" href="/assets/js/20.c5f96e71.js"><link rel="prefetch" href="/assets/js/21.3f0b334e.js"><link rel="prefetch" href="/assets/js/22.55c868be.js"><link rel="prefetch" href="/assets/js/23.91286241.js"><link rel="prefetch" href="/assets/js/24.c1af1909.js"><link rel="prefetch" href="/assets/js/25.a995a755.js"><link rel="prefetch" href="/assets/js/27.1eb62850.js"><link rel="prefetch" href="/assets/js/28.b383a871.js"><link rel="prefetch" href="/assets/js/29.088e0d73.js"><link rel="prefetch" href="/assets/js/3.cd716564.js"><link rel="prefetch" href="/assets/js/30.3ccc98d5.js"><link rel="prefetch" href="/assets/js/31.aab7cc23.js"><link rel="prefetch" href="/assets/js/32.5e16b7e6.js"><link rel="prefetch" href="/assets/js/33.4aaeb741.js"><link rel="prefetch" href="/assets/js/34.45e8e898.js"><link rel="prefetch" href="/assets/js/35.5899c97a.js"><link rel="prefetch" href="/assets/js/36.32e2e263.js"><link rel="prefetch" href="/assets/js/37.c4e27bbd.js"><link rel="prefetch" href="/assets/js/38.fe5e60d2.js"><link rel="prefetch" href="/assets/js/39.2cb0b4ee.js"><link rel="prefetch" href="/assets/js/4.edf4d5e7.js"><link rel="prefetch" href="/assets/js/40.08d5bead.js"><link rel="prefetch" href="/assets/js/41.2f80f24b.js"><link rel="prefetch" href="/assets/js/42.43a49913.js"><link rel="prefetch" href="/assets/js/43.08da7ec2.js"><link rel="prefetch" href="/assets/js/44.7c7cb8a9.js"><link rel="prefetch" href="/assets/js/45.0ddf7e7f.js"><link rel="prefetch" href="/assets/js/46.7c4609a5.js"><link rel="prefetch" href="/assets/js/47.edf3ddf8.js"><link rel="prefetch" href="/assets/js/48.569a90b9.js"><link rel="prefetch" href="/assets/js/49.fa368ac8.js"><link rel="prefetch" href="/assets/js/5.24054156.js"><link rel="prefetch" href="/assets/js/50.b9b3ea7f.js"><link rel="prefetch" href="/assets/js/51.a2ebf0fe.js"><link rel="prefetch" href="/assets/js/52.31f02238.js"><link rel="prefetch" href="/assets/js/53.4110ef1e.js"><link rel="prefetch" href="/assets/js/54.dab741c7.js"><link rel="prefetch" href="/assets/js/55.f27984e9.js"><link rel="prefetch" href="/assets/js/56.bd4c1a8e.js"><link rel="prefetch" href="/assets/js/57.375d40cb.js"><link rel="prefetch" href="/assets/js/58.932e3864.js"><link rel="prefetch" href="/assets/js/59.e657be1b.js"><link rel="prefetch" href="/assets/js/6.b259c061.js"><link rel="prefetch" href="/assets/js/60.88d94274.js"><link rel="prefetch" href="/assets/js/61.fa71d884.js"><link rel="prefetch" href="/assets/js/62.a9d3b3b7.js"><link rel="prefetch" href="/assets/js/63.f849fe75.js"><link rel="prefetch" href="/assets/js/64.1770f7a9.js"><link rel="prefetch" href="/assets/js/65.6afc33db.js"><link rel="prefetch" href="/assets/js/66.799f2eb4.js"><link rel="prefetch" href="/assets/js/67.f36b2f7d.js"><link rel="prefetch" href="/assets/js/68.868cd00b.js"><link rel="prefetch" href="/assets/js/69.4c29b907.js"><link rel="prefetch" href="/assets/js/7.e34ea00f.js"><link rel="prefetch" href="/assets/js/70.1b993ed4.js"><link rel="prefetch" href="/assets/js/71.e16ad4f9.js"><link rel="prefetch" href="/assets/js/72.627505e6.js"><link rel="prefetch" href="/assets/js/73.32768e14.js"><link rel="prefetch" href="/assets/js/74.968a580d.js"><link rel="prefetch" href="/assets/js/75.42d5af3d.js"><link rel="prefetch" href="/assets/js/76.19a69d31.js"><link rel="prefetch" href="/assets/js/77.cf627a78.js"><link rel="prefetch" href="/assets/js/78.07177880.js"><link rel="prefetch" href="/assets/js/8.c4dd00ce.js"><link rel="prefetch" href="/assets/js/9.0ff73be2.js">
    <link rel="stylesheet" href="/assets/css/0.styles.ada71c49.css">
  </head>
  <body class="theme-mode-light">
    <div id="app" data-server-rendered="true"><div class="theme-container sidebar-open have-rightmenu"><header class="navbar blur"><div title="目录" class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/img/logo.png" alt="浪飞IT小栈" class="logo"> <span class="site-name can-hide">浪飞IT小栈</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link">首页</a></div><div class="nav-item"><a href="/pages/6138ae/" class="nav-link">Java速通</a></div><div class="nav-item"><a href="/pages/705b35/" class="nav-link">面试经典</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="精品项目" class="dropdown-title"><a href="/project/" class="link-title">精品项目</a> <span class="title" style="display:none;">精品项目</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>桌面端</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/pages/8143cc480faf9a11/" class="nav-link">JavaScript</a></li></ul></li><li class="dropdown-item"><h4>PC后端</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/note/javascript/" class="nav-link">项目1</a></li><li class="dropdown-subitem"><a href="/note/typescript-axios/" class="nav-link">项目二</a></li></ul></li></ul></div></div><div class="nav-item"><a href="/about/" class="nav-link">电子书</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="索引" class="dropdown-title"><a href="/archives/" class="link-title">索引</a> <span class="title" style="display:none;">索引</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/" class="nav-link">分类</a></li><li class="dropdown-item"><!----> <a href="/tags/" class="nav-link">标签</a></li><li class="dropdown-item"><!----> <a href="/archives/" class="nav-link">归档</a></li></ul></div></div><div class="nav-item"><a href="/pages/0c07b2/" class="nav-link">IT杂货铺</a></div><div class="nav-item"><a href="/archives/" class="nav-link">更多资源</a></div> <!----></nav></div></header> <div class="sidebar-mask"></div> <div class="sidebar-hover-trigger"></div> <aside class="sidebar" style="display:none;"><div class="blogger"><img src="https://cdn.jsdelivr.net/gh/langfeiyes/images-khub/avatar.jpg"> <div class="blogger-info"><h3>浪飞yes</h3> <span>无法简单的人儿~</span></div></div> <nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link">首页</a></div><div class="nav-item"><a href="/pages/6138ae/" class="nav-link">Java速通</a></div><div class="nav-item"><a href="/pages/705b35/" class="nav-link">面试经典</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="精品项目" class="dropdown-title"><a href="/project/" class="link-title">精品项目</a> <span class="title" style="display:none;">精品项目</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>桌面端</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/pages/8143cc480faf9a11/" class="nav-link">JavaScript</a></li></ul></li><li class="dropdown-item"><h4>PC后端</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/note/javascript/" class="nav-link">项目1</a></li><li class="dropdown-subitem"><a href="/note/typescript-axios/" class="nav-link">项目二</a></li></ul></li></ul></div></div><div class="nav-item"><a href="/about/" class="nav-link">电子书</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="索引" class="dropdown-title"><a href="/archives/" class="link-title">索引</a> <span class="title" style="display:none;">索引</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/" class="nav-link">分类</a></li><li class="dropdown-item"><!----> <a href="/tags/" class="nav-link">标签</a></li><li class="dropdown-item"><!----> <a href="/archives/" class="nav-link">归档</a></li></ul></div></div><div class="nav-item"><a href="/pages/0c07b2/" class="nav-link">IT杂货铺</a></div><div class="nav-item"><a href="/archives/" class="nav-link">更多资源</a></div> <!----></nav>  <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>开篇</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>基础语法</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>面向对象</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>常用类</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>基础高级</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/pages/0c7696/" class="sidebar-link">集合框架</a></li><li><a href="/pages/19e70b/" class="sidebar-link">异常机制</a></li><li><a href="/pages/a53030/" aria-current="page" class="active sidebar-link">多线程</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level2"><a href="/pages/a53030/#一、今日学习内容与目标" class="sidebar-link">一、今日学习内容与目标</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level3"><a href="/pages/a53030/#_1-1-今日学习内容" class="sidebar-link">1.1 今日学习内容</a></li><li class="sidebar-sub-header level3"><a href="/pages/a53030/#_1-2-今日学习目标" class="sidebar-link">1.2 今日学习目标</a></li></ul></li><li class="sidebar-sub-header level2"><a href="/pages/a53030/#二、线程与并发" class="sidebar-link">二、线程与并发</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level3"><a href="/pages/a53030/#_2-1-线程与进程-了解" class="sidebar-link">2.1 线程与进程（了解）</a></li><li class="sidebar-sub-header level3"><a href="/pages/a53030/#_2-2-主线程-main-了解" class="sidebar-link">2.2 主线程 main（了解）</a></li><li class="sidebar-sub-header level3"><a href="/pages/a53030/#_2-3-线程的创建和启动-掌握" class="sidebar-link">2.3 线程的创建和启动（掌握）</a></li><li class="sidebar-sub-header level4"><a href="/pages/a53030/#_2-3-1-线程体-run方法-掌握" class="sidebar-link">2.3.1 线程体-run方法（掌握）</a></li><li class="sidebar-sub-header level4"><a href="/pages/a53030/#_2-3-2-线程的启动-掌握" class="sidebar-link">2.3.2 线程的启动（掌握）</a></li><li class="sidebar-sub-header level4"><a href="/pages/a53030/#_2-3-3-继承方式vs实现方式-掌握" class="sidebar-link">2.3.3 继承方式VS实现方式（掌握）</a></li><li class="sidebar-sub-header level3"><a href="/pages/a53030/#_2-4-线程生命周期和状态-掌握" class="sidebar-link">2.4 线程生命周期和状态（掌握）</a></li><li class="sidebar-sub-header level3"><a href="/pages/a53030/#_2-5-操作线程的方法-了解" class="sidebar-link">2.5. 操作线程的方法（了解）</a></li><li class="sidebar-sub-header level4"><a href="/pages/a53030/#_2-5-1-获取当前线程" class="sidebar-link">2.5.1 获取当前线程</a></li><li class="sidebar-sub-header level4"><a href="/pages/a53030/#_2-5-2-join方法-了解" class="sidebar-link">2.5.2 join方法（了解）</a></li><li class="sidebar-sub-header level4"><a href="/pages/a53030/#_2-5-3-sleep方法-了解" class="sidebar-link">2.5.3 sleep方法（了解）</a></li><li class="sidebar-sub-header level4"><a href="/pages/a53030/#_2-5-4-线程的优先级-了解" class="sidebar-link">2.5.4 线程的优先级（了解）</a></li></ul></li><li class="sidebar-sub-header level2"><a href="/pages/a53030/#三、线程安全性" class="sidebar-link">三、线程安全性</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level3"><a href="/pages/a53030/#_3-1-线程安全导致的原因-理解" class="sidebar-link">3.1 线程安全导致的原因（理解）</a></li><li class="sidebar-sub-header level3"><a href="/pages/a53030/#_3-2-线程同步操作" class="sidebar-link">3.2 线程同步操作</a></li><li class="sidebar-sub-header level4"><a href="/pages/a53030/#_3-2-1-同步代码块-掌握" class="sidebar-link">3.2.1 同步代码块（掌握）</a></li><li class="sidebar-sub-header level4"><a href="/pages/a53030/#_3-2-2-同步方法-掌握" class="sidebar-link">3.2.2 同步方法（掌握）</a></li><li class="sidebar-sub-header level3"><a href="/pages/a53030/#_3-3-synchronized的优劣-掌握" class="sidebar-link">3.3 synchronized的优劣（掌握）</a></li></ul></li><li class="sidebar-sub-header level2"><a href="/pages/a53030/#四、小结与作业" class="sidebar-link">四、小结与作业</a></li></ul></li><li><a href="/pages/16b819/" class="sidebar-link">IO</a></li><li><a href="/pages/258730/" class="sidebar-link">单元测试与配置文件</a></li><li><a href="/pages/1fdc1c/" class="sidebar-link">反射与内省机制</a></li><li><a href="/pages/80d6e3/" class="sidebar-link">Lambda表达式</a></li><li><a href="/pages/a53dcc/" class="sidebar-link">Stream流操作</a></li><li><a href="/pages/42948c/" class="sidebar-link">注解</a></li></ul></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>数据库</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>前端技术</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>热门框架</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>前后端分离</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>权限控制</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>NoSQL</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>微服务</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>消息中间件</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>脚手架</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>技术增值</span> <span class="arrow right"></span></p> <!----></section></li></ul> </aside> <div><main class="page"><div class="theme-vdoing-wrapper "><div class="articleInfo-wrap" data-v-06225672><div class="articleInfo" data-v-06225672><ul class="breadcrumbs" data-v-06225672><li data-v-06225672><a href="/" title="首页" class="iconfont icon-home router-link-active" data-v-06225672></a></li> <li data-v-06225672><a href="/categories/?category=Java%E9%80%9F%E9%80%9A" title="分类" data-v-06225672>Java速通</a></li><li data-v-06225672><a href="/categories/?category=%E5%9F%BA%E7%A1%80%E9%AB%98%E7%BA%A7" title="分类" data-v-06225672>基础高级</a></li></ul> <div class="info" data-v-06225672><div title="作者" class="author iconfont icon-touxiang" data-v-06225672><a href="https://github.com/langfeiyes" target="_blank" title="作者" class="beLink" data-v-06225672>langfeiyes</a></div> <div title="创建时间" class="date iconfont icon-riqi" data-v-06225672><a href="javascript:;" data-v-06225672>2024-03-03</a></div> <!----></div></div></div> <!----> <div class="content-wrapper"><div class="right-menu-wrapper"><div class="right-menu-margin"><div class="right-menu-title">目录</div> <div class="right-menu-content"></div></div></div> <h1><img src="">多线程<!----></h1>  <div class="theme-vdoing-content content__default"><h1 id="多线程"><a href="#多线程" class="header-anchor">#</a> 多线程</h1> <h2 id="一、今日学习内容与目标"><a href="#一、今日学习内容与目标" class="header-anchor">#</a> 一、今日学习内容与目标</h2> <h3 id="_1-1-今日学习内容"><a href="#_1-1-今日学习内容" class="header-anchor">#</a> 1.1 今日学习内容</h3> <ul><li><p>多线程相关</p></li> <li><p>线程的创建和启动</p></li> <li><p>线程的生命周期</p></li> <li><p>线程生命周期中的各个状态</p></li> <li><p>操作线程的多个方法</p></li> <li><p>线程的同步代码块</p></li> <li><p>线程的同步方法</p></li></ul> <h3 id="_1-2-今日学习目标"><a href="#_1-2-今日学习目标" class="header-anchor">#</a> 1.2 今日学习目标</h3> <ul><li><p>了解多线程概念</p></li> <li><p>了解进程和线程的区别</p></li> <li><p>认识主线程和后台线程</p></li> <li><p>掌握线程的两种创建方式</p> <ul><li>掌握使用继承方式编写多线程</li> <li>掌握使用实现方式编写多线程</li> <li>区分继承和实现方式编写多线程的优劣</li></ul></li> <li><p>掌握线程的生命周期图</p> <ul><li>知道生命周期的状态</li> <li>掌握线程多个状态之间的转换关系</li></ul></li> <li><p>了解操作线程的方法</p></li> <li><p>掌握线程同步操作</p> <ul><li>同步代码块</li> <li>同步方法</li></ul></li></ul> <h2 id="二、线程与并发"><a href="#二、线程与并发" class="header-anchor">#</a> 二、线程与并发</h2> <h3 id="_2-1-线程与进程-了解"><a href="#_2-1-线程与进程-了解" class="header-anchor">#</a> 2.1 线程与进程（了解）</h3> <p><strong>并行和并发</strong></p> <p>并行：在同一时刻，有多个任务在多个CPU上同时执行。
并发：在同一时间段，有多个任务在单个CPU上交替执行。</p> <p>进程：进程简单地说就是在多任务操作系统中，每个独立执行的程序，所以进程也就是“正在进行的程序”。（Windows系统中,我们可以在任务管理器中看到进程）</p> <p><strong>线程</strong>：<strong>线程是进程中的子任务，是组成程序运行的基本执行单元</strong>。
当操作系统执行一个程序时，会在系统中建立一个进程，该进程必须至少建立一个线程（这个线程被称为主线程）作为这个程序运行的入口点。因此，在操作系统中运行的任何程序都至少有一个线程。</p> <p>多进程：操作系统中并发运行的多个程序。</p> <p><strong>多线程：在同一个进程中并发运行的多个子任务。</strong></p> <p>一个进程至少有一个线程，为了提高效率，可以在一个进程中开启多个子任务，这就是多线程。</p> <h3 id="_2-2-主线程-main-了解"><a href="#_2-2-主线程-main-了解" class="header-anchor">#</a> 2.2 主线程 main（了解）</h3> <p>在运行一个简单的Java程序的时候，就已经存在了两个线程，一个是主线程，一个是后台线程——维护的垃圾回收（GC线程）。主线程很特殊，在启动JVM的时候自动启动的。</p> <p>进程执行时一定会有一个主线程(main 线程)存在，主线程有能力创建其他线程。</p> <p>多个线程抢占CPU，导致程序的运行轨迹不确定。多线程的运行结果也不确定，多线程的程序复杂度提高很多。</p> <h3 id="_2-3-线程的创建和启动-掌握"><a href="#_2-3-线程的创建和启动-掌握" class="header-anchor">#</a> 2.3 线程的创建和启动（掌握）</h3> <p><strong>方式一，继承Thread类：</strong></p> <ul><li><p>自定义类继承Thread</p></li> <li><p>覆写run方法</p></li> <li><p>创建自定义类对象</p></li> <li><p>自定义类对象调用start方法</p></li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">class</span> <span class="token class-name">MyThread</span> <span class="token keyword">extends</span> <span class="token class-name">Thread</span> <span class="token punctuation">{</span>
	<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token comment">// 线程体，线程启动时，会自动调用本方法，所有这里是我们写代码的主体部分</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ThreadDemo</span> <span class="token punctuation">{</span>
	<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token class-name">MyThread</span> t <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		t<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">// 调用Thread的start方法，JVM会自动调用run方法。</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p><strong>方式二，实现Runnable 接口</strong></p> <ul><li><p>自定义类实现Runnable接口</p></li> <li><p>覆写run方法</p></li> <li><p>创建自定义类对象</p></li> <li><p>把自定类的对象作为Thread类构造器参数，并调用Thread对象start方法</p></li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">class</span> <span class="token class-name">MyRun</span> <span class="token keyword">implements</span> <span class="token class-name">Runnable</span> <span class="token punctuation">{</span>
	<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token comment">//线程体，线程启动时，会自动调用本方法，所有这里是我们写代码的主体部分</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ThreadDemo2</span> <span class="token punctuation">{</span>
	<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token class-name">MyRun</span> target <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyRun</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token class-name">Thread</span> t <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span>target<span class="token punctuation">)</span><span class="token punctuation">;</span>
		t<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><p>第一种使用起来方便，启动一个线程也方便，很多功能都在Thread类中定义好了；</p> <p>第二种方式启动得依赖于Thread，因为本身Runnable中只有run方法，请看Thread的构造方法，后期的功能拓展有优势</p> <h4 id="_2-3-1-线程体-run方法-掌握"><a href="#_2-3-1-线程体-run方法-掌握" class="header-anchor">#</a> 2.3.1 线程体-run方法（掌握）</h4> <p>不管哪种方式创建的线程，都得覆写run 方法，因为这是线程体方法，该方法在线程启动之后会自动被调用。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token comment">// 线程体，线程启动时，会自动调用本方法</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>一般而言，我们在线程体中编写线程负责的子任务，所有这里是我们写代码的主体部分</p> <p><strong>线程的执行随机性：</strong></p> <p>一旦一个线程启动之后就是一个可以独立运行的线程，等待CPU的调度( 抢占式和轮流式 )分配资源，不会因为启动它的外部线程结束而结束。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">class</span> <span class="token class-name">MyThread</span> <span class="token keyword">extends</span> <span class="token class-name">Thread</span> <span class="token punctuation">{</span>
	<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token comment">//自定义线程中的for循环打印i,线程执行时打印顺序是完全随机的。</span>
		<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;MyThread  ==&gt; &quot;</span> <span class="token operator">+</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Demo</span> <span class="token punctuation">{</span>
	<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token class-name">MyThread</span> mt <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		mt<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        
		<span class="token comment">//主线程中的for循环打印i</span>
		<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;main  ==&gt; &quot;</span> <span class="token operator">+</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br></div></div><p>多次运行该程序，观察每次运行的结果。</p> <h4 id="_2-3-2-线程的启动-掌握"><a href="#_2-3-2-线程的启动-掌握" class="header-anchor">#</a> 2.3.2 线程的启动（掌握）</h4> <p>​		启动线程必须调用线程类Thread中的start方法，该方法应该由Thread类的一个实例来调用，下面是方法签名：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span> 
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>底层会调用该线程的 run 方法。</p> <p>只有调用了线程对象的start方法才会开启一个新的线程，如果是直接调用对象的run方法不会开启新的线程，只是一个单线程。</p> <p><strong>注意：启动一个新线程，不能使用run()方法，只能使用start方法。</strong></p> <h4 id="_2-3-3-继承方式vs实现方式-掌握"><a href="#_2-3-3-继承方式vs实现方式-掌握" class="header-anchor">#</a> 2.3.3 继承方式VS实现方式（掌握）</h4> <p>当多线程并发访问同一个资源时，会导致线程出现安全性的原因，看案例。</p> <p><strong>案例：现有50张票，现在有三个窗口(A、B、C)卖这50张票。</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>因为<span class="token class-name">A</span>、<span class="token class-name">B</span>、<span class="token class-name">C</span>三个窗口可以并发卖票，此时得使用多线程技术来实现这个案例。
分析<span class="token operator">:</span> 可以定义三个线程对象，并启动线程<span class="token punctuation">.</span>
第一步：每一个窗口卖票的时候：展示窗口x自己卖出一张票，
第二步：还剩xx张票
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p><strong>使用继承方式</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TicketThread</span> <span class="token keyword">extends</span> <span class="token class-name">Thread</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">int</span> count <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token class-name">TicketThread</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">super</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token comment">// 模拟10个人买票</span>
        <span class="token keyword">for</span><span class="token punctuation">(</span> <span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span>i<span class="token operator">++</span> <span class="token punctuation">)</span><span class="token punctuation">{</span>
            <span class="token keyword">if</span><span class="token punctuation">(</span> <span class="token keyword">this</span><span class="token punctuation">.</span>count <span class="token operator">&gt;</span> <span class="token number">0</span> <span class="token punctuation">)</span><span class="token punctuation">{</span>
                count<span class="token operator">--</span><span class="token punctuation">;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token keyword">super</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot;卖出一张票，还剩&quot;</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>count <span class="token operator">+</span> <span class="token string">&quot;张&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TicketThreadDemo</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 模拟买票过程。共有 5 张票，多线程模拟卖票的过程。</span>
        <span class="token class-name">TicketWindow</span> ta <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TicketWindow</span><span class="token punctuation">(</span><span class="token string">&quot;窗口A&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">TicketWindow</span> tb <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TicketWindow</span><span class="token punctuation">(</span><span class="token string">&quot;窗口B&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">TicketWindow</span> tc <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TicketWindow</span><span class="token punctuation">(</span><span class="token string">&quot;窗口C&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        ta<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        tb<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        tc<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br></div></div><p>使用继承方式完成该案例的时候，会发现A、B、C都各自卖了50张票，为何？</p> <p><strong>使用实现方式</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Ticket</span> <span class="token keyword">implements</span> <span class="token class-name">Runnable</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">int</span> count <span class="token operator">=</span> <span class="token number">5</span><span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 模拟10个人买票</span>
        <span class="token keyword">for</span><span class="token punctuation">(</span> <span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span>i<span class="token operator">++</span> <span class="token punctuation">)</span><span class="token punctuation">{</span>

            <span class="token keyword">if</span><span class="token punctuation">(</span> <span class="token keyword">this</span><span class="token punctuation">.</span>count <span class="token operator">&gt;</span> <span class="token number">0</span> <span class="token punctuation">)</span><span class="token punctuation">{</span>
                count<span class="token operator">--</span><span class="token punctuation">;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot;卖出一张票，还剩&quot;</span> <span class="token operator">+</span> count <span class="token operator">+</span> <span class="token string">&quot;张&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TicketDemo</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 1 创建一个Runnable实现类</span>
        <span class="token class-name">Ticket</span> ticket <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Ticket</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// 2 让myRun对象的线程体(run方法)跑在3个线程中</span>
        <span class="token class-name">Thread</span> ta <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span>ticket<span class="token punctuation">,</span><span class="token string">&quot;窗口A&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span> tb <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span>ticket<span class="token punctuation">,</span><span class="token string">&quot;窗口B&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span> tc <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span>ticket<span class="token punctuation">,</span><span class="token string">&quot;窗口C&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        ta<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        tb<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        tc<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br></div></div><p>在使用实现方式的时候，我们发现A、B、C一共卖了50张票，为何？</p> <p>通过买票案例，分析继承方式和实现方式的区别：</p> <p>继承方式：</p> <ul><li><p>Java中类是单继承的，如果继承了Thread了，该类就不能再有其他的直接父类了。</p></li> <li><p>从操作上分析，继承方式更简单，获取线程名字也简单。</p></li> <li><p><strong>从多线程共享同一个资源上分析</strong>，继承方式不能多个线程共享同一个资源。</p></li></ul> <p>实现方式：</p> <ul><li><p>Java中类可以实现多接口，此时该类还可以继承其他类，并且还可以实现其他接口（设计上,更优雅）。</p></li> <li><p>从操作上分析，获取线程名字也比较复杂，得使用Thread.currentThread()来获取当前线程的引用。</p></li> <li><p><strong>从多线程共享同一个资源上分析</strong>，实现方式可以多线程共享同一个资源。</p></li></ul> <h3 id="_2-4-线程生命周期和状态-掌握"><a href="#_2-4-线程生命周期和状态-掌握" class="header-anchor">#</a> 2.4 线程生命周期和状态（掌握）</h3> <p><img src="https://cdn.jsdelivr.net/gh/langfeiyes/images-khub/image-20230307173132974.png" alt=""></p> <p><strong>新生状态</strong>
用 new 关键字建立一个线程后，该线程对象就处于新生状态。
处于新生状态的线程有自己的内存空间，通过调用 start()方法进入就绪状态。</p> <p><strong>就绪状态</strong>
处于就绪状态线程具备了运行条件，但还没分配到 CPU，处于线程就绪队列，等待系统为其分配 CPU。当系统选定一个等待执行的线程后，它就会从就绪状态进入执行状态，该动作称为“CPU 调度”。</p> <p><strong>运行状态</strong>
在运行状态的线程执行自己的run 方法中代码，<strong>直到</strong></p> <ul><li>等待某些资源而这些资源又未到达，进入阻塞状态</li> <li>正常完成任务进入死亡状态</li> <li>如果在给定的CPU时间片内没有执行结束，就会被系统给换下来回到等待执行状态（就绪状态）。</li></ul> <p><strong>阻塞状态</strong>
处于运行状态的线程在某些情况下，如：</p> <ul><li>执行了 sleep(睡眠)方法</li> <li>等待 I/O设备等资源，</li></ul> <p>将让出 CPU 并暂时停止自己运行，进入阻塞状态。
注意：在阻塞状态的线程不能进入就绪队列。只有当引起阻塞的原因消除时，如睡眠时间已到，或等待的 I/O 设备空闲下来，线程便转入就绪状态，重新到就绪队列中排队等待，被系统选中后从原来停止的位置开始继续执行。</p> <p><strong>死亡状态</strong>
死亡状态是线程生命周期中的最后一个阶段。线程死亡的原因有三个：</p> <ul><li>一是正常运行的线程完成了它的全部工作</li> <li>二是线程抛出未捕获的Exception或Error，</li> <li>三是线程被强制性地终止，如通过 stop 方法来终止一个线程(强烈不推荐使用)</li></ul> <h3 id="_2-5-操作线程的方法-了解"><a href="#_2-5-操作线程的方法-了解" class="header-anchor">#</a> 2.5. 操作线程的方法（了解）</h3> <h4 id="_2-5-1-获取当前线程"><a href="#_2-5-1-获取当前线程" class="header-anchor">#</a> 2.5.1 获取当前线程</h4> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">CurrentThreadDemo</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">{</span>
		<span class="token comment">// 获取当前线程对象</span>
        <span class="token class-name">Thread</span> thread <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>注意：这句代码在哪个线程体，获取的就是哪个线程对象</p> <h4 id="_2-5-2-join方法-了解"><a href="#_2-5-2-join方法-了解" class="header-anchor">#</a> 2.5.2 join方法（了解）</h4> <p>比如在main线程中调用了a线程的join()方法时，表示只有当a线程执行完毕时，main线程才能继续执行。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyThread</span> <span class="token keyword">extends</span> <span class="token class-name">Thread</span> <span class="token punctuation">{</span>
    
    <span class="token keyword">public</span> <span class="token class-name">MyThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token punctuation">}</span>
    
    <span class="token keyword">public</span> <span class="token class-name">MyThread</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">super</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span>i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token keyword">super</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p>案例：在主线程测试join方法</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">JoinDemo</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">{</span>

        <span class="token class-name">MyThread</span> ta <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyThread</span><span class="token punctuation">(</span><span class="token string">&quot;线程A&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        ta<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// main thread</span>
        <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span>i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            <span class="token keyword">if</span><span class="token punctuation">(</span> i <span class="token operator">==</span> <span class="token number">2</span> <span class="token punctuation">)</span><span class="token punctuation">{</span>
                <span class="token comment">// t1强制执行，直到执行结束。</span>
                ta<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;main:&quot;</span> <span class="token operator">+</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br></div></div><p>线程a的join方法表示<strong>线程a的强制执行，其他线程都阻塞</strong>，直到线程a执行完成，其他线程才会被执行。</p> <h4 id="_2-5-3-sleep方法-了解"><a href="#_2-5-3-sleep方法-了解" class="header-anchor">#</a> 2.5.3 sleep方法（了解）</h4> <p>sleep方法让正在执行的线程暂停一段时间，进入阻塞状态，<strong>常常用来模拟网络延迟</strong>，或者<strong>耗时操作</strong>等。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">static</span> <span class="token function">sleep</span><span class="token punctuation">(</span><span class="token keyword">long</span> milllis<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span>：毫秒为单位 例如：<span class="token number">1</span>s <span class="token operator">=</span> <span class="token number">1000</span>ms
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>调用sleep()后，在指定时间段之内，该线程不会获得执行的机会</p> <p>案例：在主线程测试 sleep 方法</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SleepDemo</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;主线程进入休眠5s&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;5s后主线程自动唤醒&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><h4 id="_2-5-4-线程的优先级-了解"><a href="#_2-5-4-线程的优先级-了解" class="header-anchor">#</a> 2.5.4 线程的优先级（了解）</h4> <p>每个线程都有优先级，优先级的高低只和线程获得执行机会的次数多少有关。并不是说优先级高的就一定先执行，哪个线程的先运行取决于CPU的调度；</p> <p>Thread对象的setPriority(int x)和getPriority()用来设置和获得优先级。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">PriorityDemo</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
        <span class="token comment">// 线程优先级</span>
        <span class="token class-name">MyThread</span> ta <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyThread</span><span class="token punctuation">(</span><span class="token string">&quot;线程A&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        ta<span class="token punctuation">.</span><span class="token function">setPriority</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">MyThread</span> tb <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyThread</span><span class="token punctuation">(</span><span class="token string">&quot;线程B&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        tb<span class="token punctuation">.</span><span class="token function">setPriority</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        ta<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        tb<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">/** 结论
         * 线程优先级越高，被CPU调度的可能性越大
         */</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br></div></div><h2 id="三、线程安全性"><a href="#三、线程安全性" class="header-anchor">#</a> 三、线程安全性</h2> <h3 id="_3-1-线程安全导致的原因-理解"><a href="#_3-1-线程安全导致的原因-理解" class="header-anchor">#</a> 3.1 线程安全导致的原因（理解）</h3> <p>当多线程并发访问同一个资源对象(共享资源)的时候,可能出现线程不安全的问题。</p> <p>但是，分析打印的结果，有时候发现没有问题：</p> <p>意识：看不到问题，不代表没有问题，可能是我们经验不够，或者说问题出现的不够明显。</p> <p>那么可以使用线程休眠来模拟网络延迟，让问题来得更明显一些：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//当前线程睡10毫秒,当前线程休息着,让其他线程去抢资源.      </span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>在程序中并不是使用Thread.sleep(10)之后程序才出现问题，而是使用之后，问题更明显，休眠的时间越久问题越明显，一般用10或100即可，具体根据情况而定。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyRun</span> <span class="token keyword">implements</span> <span class="token class-name">Runnable</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">int</span> count <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 模拟10个人买票</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>count <span class="token operator">&gt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token comment">// 模拟耗时操作过程()</span>
                <span class="token keyword">try</span> <span class="token punctuation">{</span>
                    <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
                
                <span class="token keyword">this</span><span class="token punctuation">.</span>count<span class="token operator">--</span><span class="token punctuation">;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot;卖出一张票，还剩&quot;</span> <span class="token operator">+</span> count <span class="token operator">+</span> <span class="token string">&quot;张&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br></div></div><p>分析运行结果，为什么有错误的结果。</p> <p>在这里，总数减1操作和打印输出剩余操作，应该是一个原子操作，也就说是一个不能分割的操作，两个步骤之间不能被其他线程插一脚。</p> <p>对于原子性操作，要么都不执行，要么都执行完成，0% / 100%</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>第一步：count<span class="token operator">--</span><span class="token punctuation">;</span>
第二步：<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot;卖出一张票，还剩&quot;</span> <span class="token operator">+</span> count <span class="token operator">+</span> <span class="token string">&quot;张&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

例如<span class="token operator">:</span> <span class="token class-name">A</span>转账<span class="token number">1000</span>给<span class="token class-name">B</span>
<span class="token number">1</span> <span class="token class-name">A</span><span class="token operator">-</span><span class="token number">1000</span>
<span class="token number">2</span> <span class="token class-name">B</span><span class="token operator">+</span><span class="token number">1000</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>**解决方案：**保证票总数减1操作和打印输出剩余操作，必须同步（理解成一起）完成。</p> <h3 id="_3-2-线程同步操作"><a href="#_3-2-线程同步操作" class="header-anchor">#</a> 3.2 线程同步操作</h3> <p>**解决思路：**A线程获得同步锁进入操作的时候，B和C线程只能在外等着，A操作结束，释放同步锁。A和B和C才有机会去抢同步锁（谁获得同步锁，谁才能执行代码）。</p> <p>通俗例子：A、B、C三个人去抢厕所的雅间，为了保证安全规定谁抢到了必须上锁，把其他人排除外雅间外面。若A抢到了，进入后应该立马上锁，B和C只能在外等着，当A释放锁出来的时候，A、B、C又开始尝试抢资源。</p> <ul><li><p>方式1：同步代码块</p></li> <li><p>方式2：同步方法</p></li></ul> <h4 id="_3-2-1-同步代码块-掌握"><a href="#_3-2-1-同步代码块-掌握" class="header-anchor">#</a> 3.2.1 同步代码块（掌握）</h4> <p>同步代码块语法:</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">synchronized</span><span class="token punctuation">(</span>同步锁<span class="token punctuation">)</span> <span class="token punctuation">{</span>
   <span class="token comment">// 需要同步操作的代码</span>
<span class="token punctuation">}</span>
同步锁，又称之为同步监听对象<span class="token operator">/</span>同步监听器<span class="token operator">/</span>互斥锁<span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>为了保证每个线程都能正常执行原子操作，Java引入了线程同步锁机制。同步锁只是一个概念，可以想象为在对象上标记了一个锁。</p> <p><strong>如何选择多线程同步代码块的同步锁？</strong></p> <ul><li>Java程序允许使用任何对象作为同步监听对象（<strong>同步锁必须是对象</strong>）。</li> <li>一般的，<strong>我们把当前并发访问的共享资源作为同步监听对象</strong>，比如此时三个线程共享的资源（？）。</li></ul> <p><strong>注意：在任何时候，最多允许一个线程拥有同步锁，谁拿到锁就执行，其他的线程只能在代码块外等着。</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyTask</span> <span class="token keyword">implements</span> <span class="token class-name">Runnable</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">int</span> count <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 模拟10个人买票</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

            <span class="token keyword">synchronized</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token comment">// 业务上不可分割的逻辑单元</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>count <span class="token operator">&gt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    
                    <span class="token keyword">try</span> <span class="token punctuation">{</span>
                    	<span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>
                    
                    <span class="token keyword">this</span><span class="token punctuation">.</span>count<span class="token operator">--</span><span class="token punctuation">;</span>
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot;卖出一张票，还剩&quot;</span> <span class="token operator">+</span> count <span class="token operator">+</span> <span class="token string">&quot;张&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>

        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br></div></div><p>此时的同步锁this表示MyTask对象，而程序中MyTask对象只有一份，故可以作为同步锁。</p> <h4 id="_3-2-2-同步方法-掌握"><a href="#_3-2-2-同步方法-掌握" class="header-anchor">#</a> 3.2.2 同步方法（掌握）</h4> <p>使用synchronized修饰的方法，就叫做同步方法。保证A线程执行该方法的时候，其他线程只能在方法外等着。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">doWork</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
     <span class="token comment">// 原子性操作</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>此时同步锁是谁——其实就是，调用当前同步方法的对象：</p> <ul><li><p>对于非static方法，同步锁就是this。</p></li> <li><p>对于static方法，同步锁就是当前方法所在类的字节码（xx.class）。</p></li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">class</span> <span class="token class-name">MyTask</span> <span class="token keyword">implements</span> <span class="token class-name">Runnable</span> <span class="token punctuation">{</span>
	<span class="token keyword">private</span> <span class="token keyword">int</span> count <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">;</span>

	<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">50</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">saleTicket</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>

	<span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">saleTicket</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>count <span class="token operator">&gt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">try</span> <span class="token punctuation">{</span>
                <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>count<span class="token operator">--</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot;卖出一张票，还剩&quot;</span> <span class="token operator">+</span> count <span class="token operator">+</span> <span class="token string">&quot;张&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br></div></div><h3 id="_3-3-synchronized的优劣-掌握"><a href="#_3-3-synchronized的优劣-掌握" class="header-anchor">#</a> 3.3 synchronized的优劣（掌握）</h3> <p>好处：保证了多线程并发访问时的同步操作，避免线程的安全性问题。</p> <p>缺点：使用synchronized的方法/代码块的性能要低一些。</p> <p>建议：尽量减小synchronized的作用域。</p> <p>面试题:</p> <ol><li><p>StringBuilder和StringBuffer的区别</p></li> <li><p>ArrayList和Vector的区别</p></li> <li><p>HashMap和Hashtable的区别</p></li></ol> <p>通过源代码会发现，主要就是方法有没有使用synchronized的区别，比如StringBuilder和StringBuffer。</p> <p><em><img src="https://cdn.jsdelivr.net/gh/langfeiyes/images-khub/stringbuilder_stringbuffer.png" alt=""></em></p> <p>因此得出结论：使用synchronized修饰的方法性能较低，但是安全性较高，反之则反。</p> <h2 id="四、小结与作业"><a href="#四、小结与作业" class="header-anchor">#</a> 四、小结与作业</h2> <ul><li>了解进程与线程概念</li> <li>了解并发与并行概念</li> <li>掌握线程创建与启动方式-建议5遍</li> <li>掌握继承生命周期与状态改变</li> <li>掌握操作线程API-建议5遍</li> <li>掌握线程安全性处理-建议5遍</li></ul></div></div>  <div class="page-edit"><!----> <div class="tags"><a href="/tags/?tag=%E7%BA%BF%E7%A8%8B" title="标签">#线程</a></div> <!----></div> <div class="page-nav-wapper"><div class="page-nav-centre-wrap"><a href="/pages/19e70b/" class="page-nav-centre page-nav-centre-prev"><div class="tooltip">异常机制</div></a> <a href="/pages/16b819/" class="page-nav-centre page-nav-centre-next"><div class="tooltip">IO</div></a></div> <div class="page-nav"><p class="inner"><span class="prev">
        ←
        <a href="/pages/19e70b/" class="prev">异常机制</a></span> <span class="next"><a href="/pages/16b819/">IO</a>→
      </span></p></div></div></div> <div class="article-list"><div class="article-title"><a href="/archives/" class="iconfont icon-bi">最近更新</a></div> <div class="article-wrapper"><dl><dd>01</dd> <dt><a href="/pages/0c07b2/"><div>
            IT杂货铺
            <!----></div></a> <span class="date">03-23</span></dt></dl><dl><dd>02</dd> <dt><a href="/pages/705b35/"><div>
            人事百问
            <!----></div></a> <span class="date">03-22</span></dt></dl><dl><dd>03</dd> <dt><a href="/pages/78eb56/"><div>
            MyBatis-Plus
            <!----></div></a> <span class="date">03-12</span></dt></dl> <dl><dd></dd> <dt><a href="/archives/" class="more">更多文章&gt;</a></dt></dl></div></div></main></div> <div class="footer"><div class="icons"><a href="mailto:langfeiyes@163.com" title="发邮件" target="_blank" class="iconfont icon-youjian"></a><a href="https://github.com/langfeiyes" title="GitHub" target="_blank" class="iconfont icon-github"></a><a href="https://music.163.com/#/playlist?id=755597173" title="听音乐" target="_blank" class="iconfont icon-erji"></a></div> 
  Theme by
  <a href="https://github.com/xugaoyi/vuepress-theme-vdoing" target="_blank" title="本站主题">Vdoing</a> 
    | Copyright © 2024-2024
    <span><a href="https://beian.miit.gov.cn/" target="_blank">粤ICP备18007927号-1</a></span></div> <div class="buttons"><div title="返回顶部" class="button blur go-to-top iconfont icon-fanhuidingbu" style="display:none;"></div> <div title="去评论" class="button blur go-to-comment iconfont icon-pinglun" style="display:none;"></div> <div title="主题模式" class="button blur theme-mode-but iconfont icon-zhuti"><ul class="select-box" style="display:none;"><li class="iconfont icon-zidong">
          跟随系统
        </li><li class="iconfont icon-rijianmoshi">
          浅色模式
        </li><li class="iconfont icon-yejianmoshi">
          深色模式
        </li><li class="iconfont icon-yuedu">
          阅读模式
        </li></ul></div></div> <!----> <!----> <!----></div><div class="global-ui"><div></div></div></div>
    <script src="/assets/js/app.a2a00aa5.js" defer></script><script src="/assets/js/2.256f807a.js" defer></script><script src="/assets/js/26.abc5dea3.js" defer></script>
  </body>
</html>
